package controller.backstage;

import com.alibaba.fastjson.JSON;
import dao.backstage.GoodsDao;
import dao.backstage.impl.GoodsDaoImpl;
import pojo.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name="selectGoodsServlet",value="/selectGoods")
public class selectGoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        resp.setCharacterEncoding("utf-8");
        String goods_name = req.getParameter("goods_name");
        String type_id = req.getParameter("type_id");
        GoodsDao goodsDao = new GoodsDaoImpl();
        System.out.println("goods_name is "+goods_name);
        System.out.println("type_id is "+type_id);

        if("*".equals(goods_name) && !"0".equals(type_id)){
            //按类型查找
            System.out.println("leixing");
            try {
                List<Goods> list = goodsDao.queryByType(Integer.parseInt(type_id));

                String s = JSON.toJSONString(list);
                resp.getWriter().write(s);
                req.setAttribute("res",s);
                System.out.println(s);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if(!"*".equals(goods_name) && "0".equals(type_id)){
            //按名称查找
            System.out.println("mingcheng");
            try {
                List<Goods> list = goodsDao.queryByName(goods_name);

                String s = JSON.toJSONString(list);
                resp.getWriter().write(s);
                req.setAttribute("res",s);
                System.out.println(s);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if("*".equals(goods_name) && "0".equals(type_id)){
            //查询全部商品
            System.out.println("quanbu");
            try {
                List<Goods> list = goodsDao.queryAll();
                String s = JSON.toJSONString(list);
                resp.getWriter().write(s);
                req.setAttribute("res",s);
                System.out.println(s);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

//        req.getRequestDispatcher("/goodsAll.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

